package mk.jug.academy.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import mk.jug.academy.model.Page;
import mk.jug.academy.model.Supporter;
import mk.jug.academy.model.SupporterStatus;

import org.springframework.stereotype.Repository;


/**
 * DAO for the {@link Supporter} entity model.
 *
 * @author Ice.Penov
 */
@Repository
public class SupporterDAO extends GenericDAO<Supporter> {
	
	/**
	 * Gets the {@link Supporter}s ordered by date,
	 * with the given status, considering the given boundaries (start,end).
	 */
	public Page<Supporter> findByStatus(final SupporterStatus status, final int start, final int end) {
		return new QueryEMContext<Page<Supporter>>() {
			@Override @SuppressWarnings("unchecked")
			public Page<Supporter> query(EntityManager em) {
				Query query = em.createQuery("Select s from mk.jug.academy.model.Supporter s where s.status = :status order by s.modified desc");
				query.setParameter("status", status);
				query.setFirstResult(start);
				query.setMaxResults(end);
				List<Supporter> list = query.getResultList();
				query = em.createQuery("Select count(s.id) from Supporter s where s.status = :status");
				query.setParameter("status", status);
				return new Page<Supporter>(initialize(list), (Integer) query.getSingleResult());
			}
		}.result();
	}	
	
	/**
	 * Fetch ACTIVE Supporter with the given email.
	 */
	public Supporter findActiveByEmail(final String email) {
		return new QueryEMContext<Supporter>() {
			@Override
			public Supporter query(EntityManager em) {
				Query query = em.createQuery("Select s from mk.jug.academy.model.Supporter s where s.email = :email and s.status = :status");
				query.setParameter("email", email);
				query.setParameter("status", SupporterStatus.ACTIVE);
				return (Supporter) query.getSingleResult();
			}
		}.result();
	}
	
	/**
	 * Fetch ANY Supporter with the given email.
	 */
	public Supporter findAnyByEmail(final String email) {
		return new QueryEMContext<Supporter>() {
			@Override
			public Supporter query(EntityManager em) {
				Query query = em.createQuery("Select s from mk.jug.academy.model.Supporter s where s.email = :email");
				query.setParameter("email", email);
				return (Supporter) query.getSingleResult();
			}
		}.result();
	}	
	
}